package cn.kw0501.tms.fliter;


import cn.kw0501.tms.service.AdminService;
import cn.kw0501.tms.utils.JsonResult;
import com.alibaba.fastjson.JSONArray;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * KJ0301
 *
 * @Description :
 * @Author : Aedes
 * @Date: 2022/7/19 10:46
 */
@Slf4j
@Component
@Order(2)
@WebFilter(urlPatterns = "/")
public class LoginFilter implements Filter {
    @Value("${info.nourl}")
    private String NofilterUrl;

    @Autowired
    private AdminService adminService;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse res = (HttpServletResponse) servletResponse;
        res.setCharacterEncoding("UTF-8");
        //确认是否过滤，如果不需要过滤直接放行
        String path = req.getServletPath();
        log.debug("访问的路径是"+path);
        if(NofilterUrl.indexOf(path)>=0){
            filterChain.doFilter(req,res);
            return;
        }

        //通过header 获取token
        String token = req.getHeader("token");
        if(token==null){
            log.debug("没有token,直接返回");
            JsonResult jsonResult = JsonResult.err(203,"你还没登录");
            PrintWriter writer = res.getWriter();
            writer.print(JSONArray.toJSONString(jsonResult));
            return;
        }

        //验证token是否存在，如果存在则放行
        if(adminService.isLogin(token)){
            filterChain.doFilter(req,res);
            return;
        }

        //如果token不存在，返回未登录或登录已过期
        log.debug("token未查到");
        JsonResult jsonResult = JsonResult.err(1022,"未登录或登录已过期");
        PrintWriter writer = res.getWriter();
        writer.print(JSONArray.toJSONString(jsonResult));
    }


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.debug("登录过滤器已启动");
        Filter.super.init(filterConfig);
    }


    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}


